package net.spider.bttiantang;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;
import org.viva.api.HTTPUtils;
import org.viva.entity.cms.ContentRes;
import org.viva.entity.cms.Movie;

import net.spider.tools.page.MatchType;
import net.spider.tools.page.PageHelper;
import net.spider.tools.page.PickUpItem;

public class MovieDetail {
    String baseUrl = "http://www.bttiantang.com";

    /**
     * 获取Movie信息
     * 
     * @param url
     * @return
     * @throws IOException
     */

    public Movie getMovie(Movie movie) {
        return getMovieByDetailUrl(movie);
    }

    public Movie getMovieByDetailUrl(Movie movie) {
        String url = movie.getSurl();
        Map<String, List<PickUpItem>> detailPageOfPickUpItem = getDetailPage(url);
        List<PickUpItem> torrentsInfo = detailPageOfPickUpItem.get("tinfo");
        for (PickUpItem torrent : torrentsInfo) {
            // 这里处理torrent信息
            movie.getContentRes().add(getTorrentForPickUpItemOfBtTT(torrent, movie));
        }
        // movie.setTorrentInfo(builder.toString());
        List<PickUpItem> moviedteailsOfTagLi = detailPageOfPickUpItem.get("moviedteailsOfTagLi");
        for (PickUpItem detailsItem : moviedteailsOfTagLi) {
            // 这里处理电影的基本信息字段
            String text = detailsItem.getTargetElement().html().trim();
            if (text.indexOf("又名:") == 0) {
                movie.setCname(getElementsTextSplitByComma(detailsItem.getTargetElement().getElementsByTag("a")));
            } else if (text.indexOf("标签:") == 0) {
                movie.setTags(getElementsTextSplitByComma(detailsItem.getTargetElement().getElementsByTag("a")));
            } else if (text.indexOf("地区:") == 0) {
                movie.setArea(getElementsTextSplitByComma(detailsItem.getTargetElement().getElementsByTag("a")));
            } else if (text.indexOf("年份:") == 0) {
                // 这里已经获取，不重新设置值
            } else if (text.indexOf("导演:") == 0) {
                movie.setDirector(getElementsTextSplitByComma(detailsItem.getTargetElement().getElementsByTag("a")));
            } else if (text.indexOf("编剧:") == 0) {
                // movie.setBianJu(getElementsTextSplitByComma(detailsItem.getTargetElement().getElementsByTag("a")));
            } else if (text.indexOf("主演:") == 0) {
                movie.setActors(getElementsTextSplitByComma(detailsItem.getTargetElement().getElementsByTag("a")));
            } else if (text.indexOf("详情:") == 0) {
                // 这里拿到的是可以获取豆瓣连接的一个中转地址
                // movie.setDoubanUrl(baseUrl +
                // detailsItem.getTargetElement().attr("href"));
            } else if (text.indexOf("imdb:") == 0) {
                movie.setImdb(getElementsTextSplitByComma(detailsItem.getTargetElement().getElementsByTag("a")));
            }
        }

        return movie;
    }

    private String getElementsTextSplitByComma(Elements eles) {
        StringBuilder buider = new StringBuilder();
        if (null != eles) {
            for (Element ele : eles) {
                if (StringUtils.isEmpty(buider.toString())) {
                    buider.append(ele.text());
                } else {
                    buider.append(",").append(ele.text());
                }
            }
        }
        return buider.toString();
    }

    public Map<String, List<PickUpItem>> getDetailPage(String url) {
        String detailPage = HTTPUtils.doGet(url);
        // 构建提取内容
        List<PickUpItem> items = getPickUpItems();
        // 提取内容
        PageHelper page = new PageHelper();
        page.setDocument(Jsoup.parse(detailPage));
        page.addAllPatternParts(items);
        return page.run();
    }

    // 这里处理torrent信息
    private ContentRes getTorrentForPickUpItemOfBtTT(PickUpItem torrentItem, Movie movie) {
        ContentRes torrent = new ContentRes();
        Element tagA = torrentItem.getTargetElement().getElementsByTag("a").get(0);
        torrent.setName(tagA.attr("title").trim());
        torrent.setUrl(baseUrl + tagA.attr("href"));
        torrent.setSizeStr(tagA.getElementsByTag("em").text());
        torrent.setSource("BT");
        torrent.setContent(movie);
        return torrent;
    }

    private List<PickUpItem> getPickUpItems() {
        List<PickUpItem> targetList = new ArrayList<PickUpItem>();

        Map<String, String> cssPatterns = new HashMap<String, String>();
        cssPatterns.put("tinfo", "div.viewbox > div.sl.cl > .tinfo");
        cssPatterns.put("moviedteailsOfTagLi", ".viewbox > .moviedteail > .moviedteail_list > li");

        Iterator<String> iterator = cssPatterns.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();

            PickUpItem item = new PickUpItem();
            item.setMatchType(MatchType.Css);
            item.setName(key);
            item.setPattern(cssPatterns.get(key));
            targetList.add(item);
        }

        return targetList;
    }

}
